import { Module } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import weaviate from 'weaviate-client';

import { EmbeddingsModule } from '../embeddings/embeddings.module';
import { WeaviateService } from './weaviate.service';

@Module({
  exports: [WeaviateService],
  imports: [EmbeddingsModule],
  providers: [
    WeaviateService,
    {
      provide: 'WEAVIATE_CLIENT',
      inject: [ConfigService],
      useFactory: async (configService: ConfigService) => {
        const connectServer = async () => {
          const weaviateClient = await weaviate.connectToLocal({
            host: configService.get<string>('WEAVIATE_URL'),
            port: configService.get<number>('WEAVIATE_PORT'),
            grpcPort: configService.get<number>('WEAVIATE_GRPC_PORT'),
          });
          return weaviateClient;
        };

        const retries = 10;
        const delay = 5000;
        for (let i = 0; i < retries; i++) {
          try {
            const client = await connectServer();
            if (client) {
              return client;
            }
          } catch {
            console.log(`Weaviate not ready yet, retrying... (${i + 1}/${retries})`);
          }
          await new Promise((resolve) => setTimeout(resolve, delay));
        }

        throw new Error('Weaviate not ready after retries');
      },
    },
  ],
})
export class WeaviateModule {}
